package model

import (
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"myginblog/utils/errmsg"
)

type Article struct {
	Category Category `gorm:"foreignkey:Cid"`
	gorm.Model
	Title        string `gorm:"type:varchar(100);not null " json:"title"`
	Cid          int    `gorm:"type:int;not null" json:"cid"`
	Desc         string `gorm:"type:varchar(200)" json:"desc"`
	Content      string `gorm:"type:longtext" json:"content"`
	Img          string `gorm:"type:varchar(100)" json:"img"`
	CommentCount int    `gorm:"type:int;not null;default:0" json:"comment_count"`
	ReadCount    int    `gorm:"type:int;not null;default:0" json:"read_count"`
}

// CreatArticle 新增分类
func CreatArticle(data *Article) int {
	err = db.Create(&data).Error
	if err != nil {
		log.Error(err)
		//	500
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// GetCateArticle 查询分类下的所有文章
func GetCateArticle(id int, pageSize int, pageNum int) ([]Article, int, int64) {
	var cateArtList []Article
	var total int64

	err = db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where(
		"cid =?", id).Find(&cateArtList).Error
	db.Model(&cateArtList).Where("cid =?", id).Count(&total)
	if err != nil {
		return nil, errmsg.ErrorCateNotExist, 0
	}
	return cateArtList, errmsg.SUCCESS, total
}

// GetArticleInfo 查询单个文章
func GetArticleInfo(id int) (Article, int) {
	var art Article
	err = db.Where("id = ?", id).Preload("Category").First(&art).Error
	db.Model(&art).Where("id = ?", id).UpdateColumn("read_count", gorm.Expr("read_count + ?", 1))
	if err != nil {
		return art, errmsg.ErrorArtNotExist
	}
	return art, errmsg.SUCCESS
}

// GetArticle 查询文章列表
func GetArticle(pageSize int, pageNum int) ([]Article, int) {
	var article []Article
	err = db.Preload("Categories").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		log.Error(err)
		return nil, errmsg.ERROR
	}
	return article, errmsg.SUCCESS
}

// EditArticle 编辑文章
func EditArticle(id int, data *Article) int {
	var article Article
	var artMap = make(map[string]interface{})
	artMap["title"] = data.Title
	artMap["cid"] = data.Cid
	artMap["desc"] = data.Desc
	artMap["content"] = data.Content
	artMap["img"] = data.Img
	err = db.Model(&article).Where("id = ? ", id).Updates(artMap).Error
	if err != nil {
		log.Error(err)
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// DeleteArticle 删除文章
func DeleteArticle(id int) int {
	var article Article
	err = db.Where("id = ? ", id).Delete(&article).Error
	if err != nil {
		log.Error(err)
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
